import { Ref, ref } from "vue";
import { DataGridHeaderCell, UseDataView, UseFilterHistory, UseVirtualScroll } from "../../composition/types";
import { Tag } from "../../../../tags";

export default function (
    headerCell: DataGridHeaderCell,
    gridContentRef: Ref<any>,
    rightFixedGridContentRef: Ref<any>,
    useDataViewComposition: UseDataView,
    useFilterHistoryComposition: UseFilterHistory,
    useVirtualScrollComposition: UseVirtualScroll
) {
    headerCell.filterHistory = headerCell.filterHistory || useFilterHistoryComposition.getFilterHistory(headerCell);
    headerCell.filter = headerCell.filter || function (dataItem: any) {
        return ((dataItem[headerCell.field] || '') as string).startsWith(headerCell.filterValue);
    };

    function onRemoveHistoryTag(tagToRemove: Tag, index: number) {
        useFilterHistoryComposition.removeFilterHistory(headerCell, tagToRemove.name);
        headerCell.filterHistory = useFilterHistoryComposition.getFilterHistory(headerCell);
    }

    function onSelectHistoryTag(currentTag: Tag) {
        headerCell.filterValue = currentTag.name;
    }

    function onUpdateHistoryTags(tags: Tag[]) {
        headerCell.filterHistory = tags;
    }

    const originalValues = useDataViewComposition.rawView.value.reduce((values: any[], dataItem: any, index: number) => {
        values.push(dataItem[headerCell.field]);
        return values;
    }, []);
    const recommendedDataValues = [...new Set(originalValues)];
    const recommendedData = recommendedDataValues.map((value: any, index: number) => {
        return { id: index, name: value };
    });

    return <div style="display:flex;flex-direction:column;">
        <f-search-box v-model={headerCell.filterValue}
            popup-host={gridContentRef.value} popup-right-boundary={rightFixedGridContentRef.value}
            popup-offset-x={useVirtualScrollComposition.offsetX}
            recommended-data={recommendedData}
        ></f-search-box>
        <f-tags style="margin-top:10px" tag-type="default" data={headerCell.filterHistory}
            show-close={true} selectable={true} onRemove={onRemoveHistoryTag} onSelectionChange={onSelectHistoryTag}
            onChange={onUpdateHistoryTags}></f-tags>
    </div>;
}
